/**   
* @Title: HbaseTestCase.java 
* @Package com.hbaseapi 
* @Description: TODO(用一句话描述该文件做什么) 
* @author 安天池   
* @date 2016年12月14日 下午1:52:29 
* JDK版本：1.8
* @version V1.0   
*/
package com.hbaseapi;

import java.io.IOException;
import java.util.Random;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

/** 
* @ClassName: HbaseTestCase 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author 安天池
* @date 2016年12月14日 下午1:52:29 
*  
*/
public class HbaseTestCase {

	//声明静态配置
	static Configuration cfg = HBaseConfiguration.create();
	
	//创建一张表，通过HBASEADMIN 和HbaseDescripter来创建
	public static void createTable(String tableName,String columnFamily) throws MasterNotRunningException, ZooKeeperConnectionException, IOException{
		@SuppressWarnings({ "deprecation", "resource" })
		HBaseAdmin admin = new HBaseAdmin(cfg);
		if(admin.tableExists(tableName) == false){
			@SuppressWarnings("deprecation")
			HTableDescriptor tableDesc = new HTableDescriptor(tableName);
			tableDesc.addFamily(new HColumnDescriptor(columnFamily));
			admin.createTable(tableDesc);
			System.out.println("表已经成功创建");
		}else{
			System.out.println("此表名字已经存在，请重新输入表名");
		}
	}
	
	@SuppressWarnings("deprecation")
	public static void putData(String tableName,String row,String columnFamily,
			String column,String data) throws IOException{
		HTable htable = new HTable(cfg, tableName);
		Put put = new Put(Bytes.toBytes(row));
		put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(data));
		htable.put(put);
		System.out.println("数据添加完毕。");
	}
	
	/**
	 * @throws IOException 
	 * @throws ZooKeeperConnectionException 
	 * @throws MasterNotRunningException  
	* @Title: HbaseTestCase
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param args    设定文件 
	* @return    返回类型 
	* @throws 
	*/
	public static void main(String[] args) throws MasterNotRunningException, ZooKeeperConnectionException, IOException {
		// TODO Auto-generated method stub

		Random r = new Random();
		String tableName = "test1";
		String columnFamily = "f1";
		String row = "r1";
		String column ="c1";
		String data = "数据" + r.nextDouble();
		createTable(tableName, columnFamily);
		putData(tableName, row, columnFamily, column, data);
	}

}
